(function(){
	angular.module('app').directive('charts', ['$rootScope',function ($rootScope) {
		return {
			restrict: 'A',
			scope:{
				chartsLink: '&',
				chartsLoad: '='
			},
			link: function (scope, ele, attr) {

				scope.chart = echarts.init(ele[0]);

				console.log(scope.chartsLoad);


				scope.$watch('chartsLoad',function(newValue,oldValue){

					console.log('oldValue:'+oldValue+' newValue:'+newValue);

					if(newValue){
						scope.chart.clear();
                    	scope.chart.showLoading();
					}else{
						scope.chart.hideLoading();
					}
				});


                var clearFunc = $rootScope.$on('echart_draw_EV', function(e, data,target_id) {
                    // console.log('注意，要画图了...');
          			if(target_id === attr.id){
						 data = chartPieResize(data);
						 scope.chart.setOption(data);
						 scope.chart.hideLoading();
						 if (scope.chartsLink) {
						     console.log(typeof scope.chartsLink);
						     scope.chart.on('click', scope.chartsLink());
						 }

          			}
                   
                });

                function chartPieResize(data) {
                    if (data.series[0].type == 'pie') {
                        var width = document.body.clientWidth;
                        var height = document.body.clientHeight;
                        // console.log((width / height).toFixed(2));
                        if ((width / height).toFixed(2) > 1.0) {
                            data.series[0].radius = '48%';
                        }

                        if(document.body.clientWidth<415){
                            data.series[0].radius = '40%';
                        }

                    }
                    // console.log(data);
                    return data;

                }

                scope.$on('$destroy', function() {
                    clearFunc();
                    scope.chart.off('click');
                });
				
			}
		};
	}])
})();